﻿/*
 * 由SharpDevelop创建。
 * 用户： zhwang
 * 日期: 2020/2/24
 * 时间: 23:21
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
 
 //3.24更新文档名称排序，更新图框块分组及按照页码排序
 
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
//using System.Windows.Forms;
using ACAD = Autodesk.AutoCAD.ApplicationServices;
using System.Runtime.InteropServices;
using Autodesk.AutoCAD.Geometry;
using System.IO;

namespace Plot08
{
    /// <summary>
    /// Description of PlotAllDwg.
    /// </summary>
    public class PlotAllDwg
	{

		public PlotAllDwg()
		{
		}

        /// <summary>
        /// 批量打印已经打开文档图纸空间的所有图框块
        /// </summary>
        [CommandMethod("mpall", CommandFlags.Session)]
        public void _plotAllDwgs_inLayout()
        {
            bool plotModelorPaperSpace = false;//True for Model,false for Paper

            #region 变量定义

            List<string> nameS_Dwgs = new List<string>();

            List<string> list_Dwgs = new List<string>();

            Editor acEd_tmp = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            //ACAD.DocumentCollection docColS = ACAD.Application.DocumentManager;
    
            //List<Document> noSortdocCol=new List<Document>();
            
            //foreach (Document element in docColS) {
            	
            //    noSortdocCol.Add(element);
            	
            //}
            
            //noSortdocCol.OrderBy(d=>d.Name);

            List<Document> docCol = new List<Document>();

            // docCol=noSortdocCol.ToList();


             GetSortedDocs(acEd_tmp, out docCol);

            foreach (var element in docCol) {
            	
             	acEd_tmp.WriteMessage(element.Name+"\n");
             	
            }
             
             
            string activeFileName=string.Empty;
   

            string aPlotSetingsName = string.Empty;
            
            #endregion

            #region 获取图框块名称记录文件Tk.xml及页面设置所在的dwg文件路径.

            string dwgFilePath = "";

            string sAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            string shortNameDllFileName = System.IO.Path.GetFileName(sAssemblyPath);

            dwgFilePath = sAssemblyPath.Replace(shortNameDllFileName, "DeaufltPlotSetings.dwg");

            string xmlFilePath = string.Empty;

            xmlFilePath = sAssemblyPath.Replace(shortNameDllFileName, "Tk.xml");

            string printLogTxt = sAssemblyPath.Replace(shortNameDllFileName, "printLog.txt");



            #endregion

            #region 读入TK.xm文件中的记录的图框块名称到blockNames

            List<string> blockNames = new List<string>();

            if (System.IO.File.Exists(xmlFilePath))
            {

                XmlTool Tool = new XmlTool(xmlFilePath);

                foreach (var item in Tool.Get_TkNameInfo())
                {
                    blockNames.Add(item);
                }

            }
            else
            {
                ACAD.Application.ShowAlertDialog("没有找到图框块名称记录文件Tk.xml,程序无法运行");

                return;

            }

            #endregion

            #region 设置打印单位 

            object o = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("measurement");

            int svShort = Convert.ToInt16(o);

               Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", 1);
            
            if (svShort == 0)
            {

                acEd_tmp.WriteMessage("本程序默认使用公制单位进行打印，本图为英制图纸，将临时调整为公制进行打印，打印后恢复为英制");

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", 1);

            }
            #endregion

            #region 获取当前布局的BlockTableRecordId，用于后面关联页面设置，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            ObjectId curLayoutId = ObjectId.Null;

            bool isModel = true;

            //获取当前空间的BlockTableRecordId，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            curLayoutId = LayoutTool.GetCurSpaceObjectId(out isModel);

            #endregion

            plotModelorPaperSpace = isModel;

            #region 确定要使用的页面设置名称aPlotSetingsName，并说拟打印的空间名称

            string detials = string.Empty;

            bool b = GetPlotSetingsName(acEd_tmp, dwgFilePath, isModel, out aPlotSetingsName, out detials);

            if (b == false || aPlotSetingsName == string.Empty)
            {

                ACAD.Application.ShowAlertDialog("没有选取适合的页面设置，无法进行打印，谢谢使用");

                return;

            }

            if (plotModelorPaperSpace==true)
            {

                string str = "记录文件中，找到适用于< 模型空间 >进行打印的页面设置，具体为" + detials;

                string caption = "注意，仅打印<-模型空间->的图框，是与否继续？";

                if (System.Windows.Forms.MessageBox.Show(str, caption, System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) != System.Windows.Forms.DialogResult.Yes)
                {
                    return;
                }
  
                //ACAD.Application.ShowAlertDialog("将采用名称<-" + aPlotSetingsName + "->的页面设置"+detials + "打印" + docCol.Count.ToString() + "文档中<-----模型空间----->图框");

                //ACAD.Application.ShowAlertDialog("将采用"+detials + "打印" + docCol.Count.ToString() + "文档中<-----模型空间----->图框");

            }
            else
            {
                string str = "记录文件中，找到适用于< 图纸空间 >进行打印的页面设置，具体为" + detials;

                string caption = "注意，仅打印<-图纸空间->的图框，是与否继续？";

                if (System.Windows.Forms.MessageBox.Show(str, caption, System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) != System.Windows.Forms.DialogResult.Yes)
                {
                    return;
                }
            }


              #endregion

            //定义了一个委托，关联到DocumentActive的时间
            ACAD.Application.DocumentManager.DocumentActivated += new DocumentCollectionEventHandler(docChange);
   

            foreach (var item in docCol)
            {
                System.Threading.Thread.Sleep(5000);

                List<ObjectId> layoutIds = new List<ObjectId>();

                List<Layout> layouts = new List<Layout>();

                Document dItem = item as Document;

                #region 统一当前工作数据库与当前显示文档,如果不统一会报错的
                try
                {

                    if (HostApplicationServices.WorkingDatabase != dItem.Database)
                    {

                        HostApplicationServices.WorkingDatabase = dItem.Database;

                        Application.DocumentManager.MdiActiveDocument = dItem;

                    }

                }
                catch (Autodesk.AutoCAD.Runtime.Exception e)
                {

                    ACAD.Application.ShowAlertDialog("当前文档与当前数据库不对应，程序出错" + e.Message.ToString());

                    return;
                }
      
                activeFileName=dItem.Name;
                
                   Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", 1);
                
                #endregion

                using (dItem.LockDocument())
                {
  
                    #region 自记录文件导入名称为aPlotSetingsName的页面设置，导入不成功会退出打印程序

                    //如果导入不成功，说明相关原因

                    bool getInPlotSetings = LayoutTool.GetInAtPlotSetings(dwgFilePath, aPlotSetingsName, plotModelorPaperSpace);

                    if (getInPlotSetings == false)
                    {
                        ACAD.Application.ShowAlertDialog("没有找到所需的页面设置名称,程序放弃打印");

                        return;
                    }

                    #endregion

                    #region 关联页面设置到布局 

                    Database acDb = dItem.Database;

                    using (Transaction acTrans = acDb.TransactionManager.StartTransaction())
                    {
                        DBDictionary LayoutDB = acTrans.GetObject(acDb.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;

                        // Step through and list each named layout and Model
                        foreach (DBDictionaryEntry itemDb in LayoutDB)
                        {
                            //acDoc.Editor.WriteMessage("\n  " + item.Key);

                            if (plotModelorPaperSpace == true)
                            {
                                if (itemDb.Key.ToString().ToUpper().Contains("MODEL") == true)
                                {

                                    if (LayoutTool.AssignPage_SetupToLayout(itemDb.Value, aPlotSetingsName) == false)
                                    {
                                        //Application.ShowAlertDialog(item.Name+itemDb.Key.ToString() + "关联页面设置到布局失败，跳过打印");
                                      
                                        WriteTxt(item.Name + itemDb.Key.ToString() + "关联页面设置到布局失败，跳过打印，建议设置好页面设置后，采用MP命令进行打印", printLogTxt);
                                       
                                        continue;

                                    }
                                    else
                                    {
                                        layoutIds.Add(itemDb.Value);
                                    }

                                }

                            }
                            else
                            {
                                if (itemDb.Key.ToString().ToUpper().Contains("MODEL") == false)
                                {

                                    if (LayoutTool.AssignPage_SetupToLayout(itemDb.Value, aPlotSetingsName) == false)
                                    {
                                        //Application.ShowAlertDialog(item.Name+itemDb.Key.ToString() + "关联页面设置到布局失败，跳过打印");

                                        WriteTxt(item.Name + itemDb.Key.ToString() + "关联页面设置到布局失败，跳过打印，建议设置好页面设置后，采用MP命令进行打印", printLogTxt);

                                        continue;

                                    }
                                    else
                                    {
                                        layoutIds.Add(itemDb.Value);
                                    }

                                }

                            }

                        }

                        acTrans.Commit();

                    }

                    #endregion

                    #region 最终的打印核心代码

                    using (Transaction acTrans = acDb.TransactionManager.StartTransaction())
                    {
                        DBDictionary LayoutDB = acTrans.GetObject(acDb.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;

                        foreach (ObjectId oid in layoutIds)
                        {
                            Layout layout = acTrans.GetObject(oid, OpenMode.ForRead) as Layout;

                            layouts.Add(layout);

                        }
                        List<Layout> layoutS = new List<Layout>();

                        layoutS = layouts.OrderBy(layout => layout.TabOrder).ToList<Layout>();

                        //ACAD.Application.ShowAlertDialog(layoutS.Count.ToString());

                        foreach (Layout layout_cur in layoutS)
                        {
                            System.Threading.Thread.Sleep(5000);

                            BlockTableRecord btr = acTrans.GetObject(layout_cur.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord;

                            LayoutManager lm = LayoutManager.Current;

                            lm.CurrentLayout = layout_cur.LayoutName;

                            DBDictionary acPlSet = acTrans.GetObject(acDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;

                            PlotSettings plSet = null;

                            //ACAD.Application.ShowAlertDialog(acPlSet.Contains(aPlotSetingsName).ToString());

                            // Check to see if the page setup exists
                            if (acPlSet.Contains(aPlotSetingsName) == true)
                            {
                                plSet = acPlSet.GetAt(aPlotSetingsName).GetObject(OpenMode.ForRead) as PlotSettings;

                            }

                            //List<ObjectId> blockIds = LayoutTool.Get_tk_BlocksIds(blockNames);

                            #region 图框块的相关处理

                            List<BlockReference> blocks = new List<BlockReference>();

                            if (plotModelorPaperSpace==true)
                            {
                                blocks = LayoutTool.Get_tk_BlocksAuto(blockNames, "MODEL");
                            }
                            else
                            {
                                blocks = LayoutTool.Get_tk_BlocksAuto(blockNames, "PAPER");
                            }


                            //ACAD.Application.ShowAlertDialog(blocks.Count.ToString());

                            List<BlockReference> blocksInLayout = new List<BlockReference>();

                            blocksInLayout.Clear();

                            foreach (var block in blocks)
                            {
                                if (block.OwnerId == layout_cur.BlockTableRecordId)
                                {
                                    blocksInLayout.Add(block);

                                }
                            }
                            //这里还可以加一个图框块按照坐标排序的功能

                            //按照Z形排列打印图纸

                            List<BlockReference> tks = new List<BlockReference>();
                            
                            try {
                            	
                            		tks=PlotWin.GetGroupedAndOrderedTks(blocksInLayout);
                            		
                            } catch (System.Exception) {
                            	
                            	
                            	   tks = blocksInLayout.OrderByDescending(tk => tk.Position.Y).ThenBy(tk => tk.Position.X).ToList<BlockReference>();
                            	   
//                            	throw;
                            }
                            
                            

                         

                            //ACAD.Application.ShowAlertDialog(tks.Count.ToString());

                            #endregion

                            #region 逐个图框块进行打印

                            int i = 0;

                            foreach (var block in tks)
                            {
                                Extents2d window = LayoutTool.GetBlockExtent2d(block);

                                #region 设置pdf文件的名称

                                string name = string.Empty;

                                if (blocksInLayout.Count > 1)
                                {
                                    name = layout_cur.LayoutName + "--" + i;
                                }
                                else
                                {
                                    name = layout_cur.LayoutName;
                                }

                                string shortName = System.IO.Path.GetFileNameWithoutExtension(activeFileName) + "-";

                                name = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(activeFileName), shortName + name);


                                #endregion

                                //如果页面设置没有问题就进行打印咯

                                if (plSet != null)
                                {
                                    //ACAD.Application.ShowAlertDialog("wo yun xing dao zhe li le ");

                                    //bool bb = LayoutTool.PlotWindowByCurPlotSetting(window, name);

                                    System.Threading.Thread.Sleep(1000);

                                    bool bb = LayoutTool.PlotWindowByCurPlotSetting(block, name);


                                }

                                i++;
                            }

                            #endregion



                        }

                        acTrans.Abort();
                    }

                    #endregion
                    
                }


            }

            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", o);

            //************************************************************************************************************************

            ///存储和更改系统 变量

            //int XREFNOTIFY = System.Convert.ToInt32(Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("XREFNOTIFY"));

            //Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("XREFNOTIFY", 0);

            //int PROXYNOTICE = System.Convert.ToInt32(Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("PROXYNOTICE"));

            //Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("PROXYNOTICE", 0);

            //Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("XREFNOTIFY", XREFNOTIFY);

            //Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("PROXYNOTICE", PROXYNOTICE);

            //Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("FILEDIA", 1);

        }

        /// <summary>
        /// 批量打印已经打开文档图纸空间的所有图框块
        /// </summary>
        [CommandMethod("mpallall", CommandFlags.Session)]
        public void _plotAllDwgs_inAllLayout()
        {

            #region 变量定义

            short flag = 0;

            List<string> nameS_Dwgs = new List<string>();

            List<string> list_Dwgs = new List<string>();

            List<Document> docCol;

            List<string> blockNames = new List<string>();

            string activeFileName = string.Empty;

            string aPlotSetingsNameForModel = string.Empty;

            string aPlotSetingsNameForPaper = string.Empty;

            Editor acEd_tmp = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            #endregion

            //排序文档

            //GetSortedDocsForAll(acEd_tmp, out docCol);

            GetSortedDocs(acEd_tmp, out docCol);


            #region 获取图框块名称记录文件Tk.xml及页面设置所在的dwg文件路径.读入TK.xm文件中的记录的图框块名称到blockNames

            string dwgFilePath = "";

            string sAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            string shortNameDllFileName = System.IO.Path.GetFileName(sAssemblyPath);

            dwgFilePath = sAssemblyPath.Replace(shortNameDllFileName, "DeaufltPlotSetings.dwg");

            bool getBlockNames = GetTkNamesFromXmlFile(out blockNames);

            if (getBlockNames == false)
            {
                return;
            }

            object o = GetSysVarOfM(acEd_tmp);     //将图纸设置为公制
            #endregion

            #region 确定要使用的页面设置名称aPlotSetingsName，并说拟打印的空间名称

            string detialsForModel = string.Empty;

            string detialsForPaper = string.Empty;

            acEd_tmp.WriteMessage("适用于模型空间的页面设置如下 \n");

            bool bForModel = GetPlotSetingsName(acEd_tmp, dwgFilePath, true, out aPlotSetingsNameForModel, out detialsForModel);

            acEd_tmp.WriteMessage("适用于图纸空间的页面设置如下 \n");

            bool bForPaper = GetPlotSetingsName(acEd_tmp, dwgFilePath, false, out aPlotSetingsNameForPaper, out detialsForPaper);

            if (bForModel == false && bForPaper == false)
            {
                Application.ShowAlertDialog("记录文件中，没有找到适用于进行批量打印的页面设置（模型空间与图纸空间均没有），程序退出");

                flag = 0;

                return;
            }

            if (bForModel == true && bForPaper == false)
            {
                if (detialsForModel != string.Empty)
                {
                    string str = "记录文件中，仅找到适用于< 模型空间 >进行打印的页面设置，具体为" + detialsForModel;

                    string caption = "注意，仅打印<-模型空间->的图框，是与否继续？";

                    if (System.Windows.Forms.MessageBox.Show(str, caption, System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        flag = 2;
                    }
                    else
                    {
                        return;
                    }

                }
                else
                {
                    return;
                }

            }

            if (bForModel == false && bForPaper == true)
            {
                string str = "记录文件中，仅找到适用于< 图纸空间 >进行打印的页面设置，具体为" + detialsForPaper;

                string caption = "注意，仅打印<-图纸空间->空间的图框，是与否继续？";

                if (System.Windows.Forms.MessageBox.Show(str, caption, System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    flag = 4;
                }
                else
                {
                    return;
                }

            }

            if (bForModel == true && bForPaper == true)
            {
                string str = "将采用" + detialsForModel + "打印< 模型空间 >,将采用" + detialsForPaper + "打印< 图纸空间 >";

                string caption = "模型空间、图纸空间图框均会进行打印，是否继续打印";

                if (System.Windows.Forms.MessageBox.Show(str, caption, System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    flag = 6;
                }
                else
                {
                    return;
                }
            }

            #endregion


            //定义了一个委托，关联到DocumentActive的时间

            //ACAD.Application.DocumentManager.DocumentActivated += new DocumentCollectionEventHandler(docChange);

            foreach (var item in docCol)
            {
                List<ObjectId> layoutIds = new List<ObjectId>();

                List<Layout> layouts = new List<Layout>();

                Document dItem = item as Document;

                #region 统一当前工作数据库与当前显示文档,如果不统一会报错的
                try
                {

                    if (HostApplicationServices.WorkingDatabase != dItem.Database)
                    {

                        HostApplicationServices.WorkingDatabase = dItem.Database;

                        Application.DocumentManager.MdiActiveDocument = dItem;

                    }

                }
                catch (Autodesk.AutoCAD.Runtime.Exception e)
                {

                    ACAD.Application.ShowAlertDialog("当前文档与当前数据库不对应，程序出错" + e.Message.ToString());

                    return;
                }

                activeFileName = dItem.Name;

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", 1);

                #endregion

                using (dItem.LockDocument())
                {

                    #region 自记录文件导入名称为aPlotSetingsName的页面设置，导入不成功会退出打印程序

                    //如果导入不成功，说明相关原因

                    bool getInPlotSetings = false;

                    if (flag == 2)
                    {
                        getInPlotSetings = LayoutTool.GetInAtPlotSetings(dwgFilePath, aPlotSetingsNameForModel, true);

                        if (getInPlotSetings == false)
                        {
                            return;
                        }
                    }
                    if (flag == 4)
                    {
                        getInPlotSetings = LayoutTool.GetInAtPlotSetings(dwgFilePath, aPlotSetingsNameForPaper, false);

                        if (getInPlotSetings == false)
                        {
                            return;
                        }
                    }

                    if (flag == 6)
                    {
                        getInPlotSetings = LayoutTool.GetInAtPlotSetings(dwgFilePath, aPlotSetingsNameForModel, true);

                        if (getInPlotSetings == false)
                        {
                            return;
                        }

                        getInPlotSetings = LayoutTool.GetInAtPlotSetings(dwgFilePath, aPlotSetingsNameForPaper, false);

                        if (getInPlotSetings == false)
                        {
                            return;
                        }

                    }

                    #endregion

                    #region 关联页面设置到布局


                    Database acDb = dItem.Database;

                    using (Transaction acTrans = acDb.TransactionManager.StartTransaction())
                    {
                        DBDictionary LayoutDB = acTrans.GetObject(acDb.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;

                        // Step through and list each named layout and Model
                        foreach (DBDictionaryEntry itemDb in LayoutDB)
                        {
                            if (flag == 2)
                            {
                                if (itemDb.Key.ToString().ToUpper().Contains("MODEL") == true)
                                {

                                    if (LayoutTool.AssignPage_SetupToLayout(itemDb.Value, aPlotSetingsNameForModel) == false)
                                    {
                                        Application.ShowAlertDialog(itemDb.Key.ToString() + "关联页面设置到布局失败，跳过打印");

                                        continue;

                                    }
                                    else
                                    {
                                        layoutIds.Add(itemDb.Value);
                                    }

                                }

                            }
                            if (flag == 4)
                            {
                                if (itemDb.Key.ToString().ToUpper().Contains("MODEL") == false)
                                {

                                    if (LayoutTool.AssignPage_SetupToLayout(itemDb.Value, aPlotSetingsNameForPaper) == false)
                                    {
                                        Application.ShowAlertDialog(itemDb.Key.ToString() + "关联页面设置到布局失败，跳过打印");

                                        continue;
                                    }
                                    else
                                    {
                                        layoutIds.Add(itemDb.Value);
                                    }



                                }

                            }

                            if (flag == 6)
                            {

                                if (itemDb.Key.ToString().ToUpper().Contains("MODEL") == true)
                                {

                                    if (LayoutTool.AssignPage_SetupToLayout(itemDb.Value, aPlotSetingsNameForModel) == false)
                                    {
                                        Application.ShowAlertDialog(itemDb.Key.ToString() + "关联页面设置到布局失败，跳过打印");

                                        continue;
                                    }
                                    else
                                    {
                                        layoutIds.Add(itemDb.Value);
                                    }

                                }

                                if (itemDb.Key.ToString().ToUpper().Contains("MODEL") == false)
                                {

                                    if (LayoutTool.AssignPage_SetupToLayout(itemDb.Value, aPlotSetingsNameForPaper) == false)
                                    {
                                        Application.ShowAlertDialog(itemDb.Key.ToString() + "关联页面设置到布局失败，跳过打印");

                                        continue;
                                    }
                                    else
                                    {
                                        layoutIds.Add(itemDb.Value);
                                    }

                                }

                            }



                        }

                        acTrans.Commit();

                    }

                    #endregion

                    #region 最终的打印核心代码

                    using (Transaction acTrans = acDb.TransactionManager.StartTransaction())
                    {
                        DBDictionary LayoutDB = acTrans.GetObject(acDb.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;


                        if (flag == 2)
                        {
                            foreach (ObjectId oid in layoutIds)
                            {
                                Layout layout = acTrans.GetObject(oid, OpenMode.ForRead) as Layout;

                                if (layout.ModelType == true)
                                {
                                    layouts.Add(layout);
                                }
                            }
                        }

                        if (flag == 4)
                        {
                            foreach (ObjectId oid in layoutIds)
                            {
                                Layout layout = acTrans.GetObject(oid, OpenMode.ForRead) as Layout;

                                if (layout.ModelType == false)
                                {
                                    layouts.Add(layout);
                                }
                            }
                        }

                        if (flag == 6)
                        {
                            foreach (ObjectId oid in layoutIds)
                            {
                                Layout layout = acTrans.GetObject(oid, OpenMode.ForRead) as Layout;

                                layouts.Add(layout);

                            }
                        }

                        List<Layout> layoutS = new List<Layout>();

                        layoutS = layouts.OrderBy(layout => layout.TabOrder).ToList<Layout>();

                        //ACAD.Application.ShowAlertDialog(layoutS.Count.ToString());

                        foreach (Layout layout_cur in layoutS)
                        {
                            BlockTableRecord btr = acTrans.GetObject(layout_cur.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord;

                            LayoutManager lm = LayoutManager.Current;

                            lm.CurrentLayout = layout_cur.LayoutName;

                        

                            //Application.ShowAlertDialog(layout_cur.ModelType.ToString());


                            DBDictionary acPlSet = acTrans.GetObject(acDb.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary;

                            PlotSettings plSet = null;

                            if (layout_cur.ModelType == true)
                            {
                                plSet = acPlSet.GetAt(aPlotSetingsNameForModel).GetObject(OpenMode.ForRead) as PlotSettings;

                            }
                            else
                            {
                                plSet = acPlSet.GetAt(aPlotSetingsNameForPaper).GetObject(OpenMode.ForRead) as PlotSettings;
                            }

                            if (plSet == null)
                            {
                                return;
                            }

                            //List<ObjectId> blockIds = LayoutTool.Get_tk_BlocksIds(blockNames);

                            #region 图框块的相关处理

                            List<BlockReference> blocks = new List<BlockReference>();

                            if (flag == 2)
                            {

                                blocks = LayoutTool.Get_tk_BlocksAuto(blockNames, "MODEL");

                            }
                            if (flag == 4)
                            {
                                blocks = LayoutTool.Get_tk_BlocksAuto(blockNames, "PAPER");
                            }
                            if (flag == 6)
                            {
                                blocks = LayoutTool.Get_tk_BlocksAuto(blockNames, "ALL");
                            }

                            //ACAD.Application.ShowAlertDialog(blocks.Count.ToString());

                            List<BlockReference> blocksInLayout = new List<BlockReference>();

                            blocksInLayout.Clear();

                            foreach (var block in blocks)
                            {
                                if (block.OwnerId == layout_cur.BlockTableRecordId)
                                {
                                    blocksInLayout.Add(block);

                                }
                            }
                            //这里还可以加一个图框块按照坐标排序的功能

                            //按照Z形排列打印图纸

                            List<BlockReference> tks = new List<BlockReference>();

                            try
                            {

                                tks = PlotWin.GetGroupedAndOrderedTks(blocksInLayout);

                            }
                            catch (System.Exception)
                            {

                                tks = blocksInLayout.OrderByDescending(tk => tk.Position.Y).ThenBy(tk => tk.Position.X).ToList<BlockReference>();

                            }

                            //ACAD.Application.ShowAlertDialog(tks.Count.ToString());

                            #endregion

                            #region 逐个图框块进行打印

                            int i = 0;

                            foreach (var block in tks)
                            {
                                //Extents2d window = LayoutTool.GetBlockExtent2d(block);

                                #region 设置pdf文件的名称

                                string name = string.Empty;

                                if (blocksInLayout.Count > 1)
                                {
                                    name = layout_cur.LayoutName + "--" + i;
                                }
                                else
                                {
                                    name = layout_cur.LayoutName;
                                }

                                string shortName = System.IO.Path.GetFileNameWithoutExtension(activeFileName) + "-";

                                name = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(activeFileName), shortName + name);


                                #endregion

                                //如果页面设置没有问题就进行打印咯

                                //ACAD.Application.ShowAlertDialog("wo yun xing dao zhe li le ");

                                //bool bb = LayoutTool.PlotWindowByCurPlotSetting(window, name);

                                bool bb = LayoutTool.PlotWindowByCurPlotSetting(block, name);



                                i++;
                            }

                            #endregion

                        }

                        acTrans.Commit();
                    }

                    #endregion

                }


            }

            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", o);

        }

        private static object GetSysVarOfM(Editor acEd_tmp)
        {
            object o = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("measurement");

            int svShort = Convert.ToInt16(o);

            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", 1);

            if (svShort == 0)
            {

                acEd_tmp.WriteMessage("本程序默认使用公制单位进行打印，本图为英制图纸，将临时调整为公制进行打印");

                Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("measurement", 1);

            }
            return o;
        }

        private static bool GetTkNamesFromXmlFile(out List<string> blockNames)
        {
            bool getTkNames = false;

            blockNames = new List<string>();

            blockNames.Clear();

            string sAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            string shortNameDllFileName = System.IO.Path.GetFileName(sAssemblyPath);

            string xmlFilePath = string.Empty;

            xmlFilePath = sAssemblyPath.Replace(shortNameDllFileName, "Tk.xml");

            if (System.IO.File.Exists(xmlFilePath))
            {

                XmlTool Tool = new XmlTool(xmlFilePath);

                foreach (var item in Tool.Get_TkNameInfo())
                {
                    blockNames.Add(item);
                }

                getTkNames = true;

            }
            else
            {
                ACAD.Application.ShowAlertDialog("没有找到图框块名称记录文件Tk.xml,程序无法运行");

                blockNames.Clear();

                getTkNames = false;

            }
            return getTkNames;
        }

        private static void GetSortedDocs(Editor acEd_tmp, out List<Document> docCol)
        {

            ACAD.DocumentCollection docColS = ACAD.Application.DocumentManager;


            List<Document> noSortdocCol = new List<Document>();

            foreach (Document element in docColS)
            {

                noSortdocCol.Add(element);

            }

            noSortdocCol.OrderBy(d => d.Name);


            var sorted = from d in noSortdocCol
                         orderby d.Name
                         select d;

            docCol = new List<Document>();

            //docCol = noSortdocCol.ToList<Document>();

            docCol = sorted.ToList<Document>();



            foreach (var element in docCol)
            {

                acEd_tmp.WriteMessage(element.Name + "\n");

            }
        }

        private static void GetSortedDocsForAll(Editor acEd_tmp, out List<Document> docCol)
        {

            ACAD.DocumentCollection docColS = ACAD.Application.DocumentManager;


            List<Document> noSortdocCol = new List<Document>();

            foreach (Document element in docColS)
            {

                noSortdocCol.Add(element);

            }

            noSortdocCol.OrderBy(d => d.Name);

            docCol = new List<Document>();

            docCol = noSortdocCol.ToList<Document>();

            foreach (var element in docCol)
            {

                acEd_tmp.WriteMessage(element.Name + "\n");

            }
        }


        /// <summary>
        /// 获取适合当前空间的页面设置序号
        /// </summary>
        /// <param name="_acEd_tmp">当前文档的Editor</param>
        /// <param name="_dwgFilepath">记录页面设置的文件的路径</param>
        /// <param name="_plotSetingsIdex">输出的有效的页面设置序号</param>
        /// <returns>如果获得了有效的页面序号则返回True否则为False</returns>
        public static bool  GetPlotSetingsIndex(Editor _acEd_tmp,string _dwgFilepath, out int _plotSetingsIdex)
        {

            _plotSetingsIdex = 0;

            ObjectId curLayoutId = ObjectId.Null;

            bool isModel = true;

            //获取当前空间的BlockTableRecordId，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            curLayoutId = LayoutTool.GetCurSpaceObjectId(out isModel);

            List<string> plotSetingsNames = new List<string>();

            List<string> plotInfoSInPlotSetings = new List<string>();

            //获取指定路径图纸中的与当前空间匹配的页面设置名称，同时输出每个匹配页面布置所对应的设置信息

            plotSetingsNames = LayoutTool.GetPlotSetingsNames(_dwgFilepath, isModel, out plotInfoSInPlotSetings);

            if (plotSetingsNames.Count == 0)
            {

                _acEd_tmp.WriteMessage("\n没有适用于当前空间的默认页面设置，请使用<svset>命令设置默认页面布局后重试");

                return false;

            }

            string aPlotSetingsName = string.Empty;

            //当只有一个的时候，在命令行输出主要页面设置信息

            //当有多个的时候，显示多个页面设置名称，及主要页面设置信息

            if (plotSetingsNames.Count == 1)
            {
                //aPlotSetingsName = plotSetingsNames[0];

                _plotSetingsIdex = 1;

                return true;

            }
            else if (plotSetingsNames.Count > 1)
            {

                _acEd_tmp.WriteMessage("\n当前空间有以下可用的页面设置：\n");

                for (int i = 0; i < plotSetingsNames.Count; i++)
                {

                    _acEd_tmp.WriteMessage(plotInfoSInPlotSetings[i] + "\n");

                }

            GetPageSetup:

                PromptIntegerOptions prompt_I = new PromptIntegerOptions("");

                prompt_I.AllowNone = true;

                prompt_I.AllowNegative = false;

                prompt_I.DefaultValue = 1;

                prompt_I.Message = "请输入需要使用的页面设置" + "[1-" + (plotSetingsNames.Count).ToString() + "]";

                PromptIntegerResult res_I;

                res_I = _acEd_tmp.GetInteger(prompt_I);

                if (res_I.Status != PromptStatus.OK)
                {

                    _acEd_tmp.WriteMessage("\n没有输入有效的页面设置选项，将放弃打印");

                    return false;

                }

                if (res_I.Value >= 1 && res_I.Value <= plotSetingsNames.Count)
                {
                    //aPlotSetingsName = plotSetingsNames[res_I.Value - 1];

                    _plotSetingsIdex = res_I.Value;

                    return true;
                }
                else
                {
                    goto GetPageSetup;

                }
                

            }

            return false;
        }

        /// <summary>
        /// 获取适合当前空间的页面设置序号
        /// </summary>
        /// <param name="_acEd_tmp">当前文档的Editor</param>
        /// <param name="_dwgFilepath">记录页面设置的文件的路径</param>
        /// <param name="_plotSetingsName">输出的有效的页面设置名称</param>
        /// <param name="_isModel">标识获取适用于模型空间或图纸空间的页面设置</param>
        /// <returns>如果获得了有效的页面序号则返回True否则为False</returns>
        public static bool GetPlotSetingsName(Editor _acEd_tmp, string _dwgFilepath,bool _isModel, out string _plotSetingsName,out string _detials )
        {

            _plotSetingsName = string.Empty;

            _detials = string.Empty;

            ObjectId curLayoutId = ObjectId.Null;

            //bool isModel = true;

            //获取当前空间的BlockTableRecordId，同时设置isModel的值，为模型空间则设置为True，否则设置为False；

            //curLayoutId = LayoutTool.GetCurSpaceObjectId(ref isModel);

            List<string> plotSetingsNames = new List<string>();

            List<string> plotInfoSInPlotSetings = new List<string>();

            //获取指定路径图纸中的与当前空间匹配的页面设置名称，同时输出每个匹配页面布置所对应的设置信息

            plotSetingsNames = LayoutTool.GetPlotSetingsNames(_dwgFilepath, _isModel, out plotInfoSInPlotSetings);

            if (plotSetingsNames.Count == 0)
            {

                _acEd_tmp.WriteMessage("\n没有适用于当前空间的默认页面设置，请使用<svset>命令设置默认页面布局后重试");

                return false;

            }

            //当只有一个的时候，在命令行输出主要页面设置信息

            //当有多个的时候，显示多个页面设置名称，及主要页面设置信息

            if (plotSetingsNames.Count == 1)
            {
                _plotSetingsName = plotSetingsNames[0];

                _detials = plotInfoSInPlotSetings[0];


                return true;

            }
            else if (plotSetingsNames.Count > 1)
            {

                _acEd_tmp.WriteMessage("\n当前空间有以下可用的页面设置：\n");

                for (int i = 0; i < plotSetingsNames.Count; i++)
                {

                    _acEd_tmp.WriteMessage(plotInfoSInPlotSetings[i] + "\n");

                }

            GetPageSetup:

                PromptIntegerOptions prompt_I = new PromptIntegerOptions("");

                prompt_I.AllowNone = true;

                prompt_I.AllowNegative = false;

                prompt_I.DefaultValue = 1;

                prompt_I.Message = "请输入需要使用的页面设置" + "[1-" + (plotSetingsNames.Count).ToString() + "]";

                PromptIntegerResult res_I;

                res_I = _acEd_tmp.GetInteger(prompt_I);

                if (res_I.Status != PromptStatus.OK)
                {

                    _acEd_tmp.WriteMessage("\n没有输入有效的页面设置选项，将放弃打印");

                    return false;

                }

                if (res_I.Value >= 1 && res_I.Value <= plotSetingsNames.Count)
                {
                    _plotSetingsName = plotSetingsNames[res_I.Value - 1];

                    _detials = plotInfoSInPlotSetings[res_I.Value - 1];

                    return true;
                }
                else
                {
                    goto GetPageSetup;

                }


            }

            return false;
        }
	

		public static void docChange(object sendObj, DocumentCollectionEventArgs docColDocActEvtArgs)
		{
			//打开成为当前活动文档后 就会执行次函数

			docColDocActEvtArgs.Document.Editor.WriteMessage(docColDocActEvtArgs.Document.Name+"切换为当前文档"+"\n");

		}

		/// <summary>
		/// 将图形对象直接加到Database里
		/// </summary>
		/// <param name="ent"></param>
		/// <param name="db"></param>
		/// <returns></returns>
		public static ObjectId AppendEntity(Entity ent, Database db)
		{
			ObjectId entId;
			using (Transaction trans = db.TransactionManager.StartTransaction()) {
				BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
				BlockTableRecord btr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
				entId = btr.AppendEntity(ent);
				trans.AddNewlyCreatedDBObject(ent, true);
				trans.Commit();
			}
			return entId;
		}
        
		public static void Delay(int milliSecond)
		{
			int start = Environment.TickCount;
			while (Math.Abs(Environment.TickCount - start) < milliSecond) {
//				Application.DoEvents();
			}
		}


        /// <summary>
        /// 写入记事本
        /// </summary>
        /// <param name="log">日志内容</param>
        /// <param name="filepath">文件路径（含文件名）</param>
        /// <returns></returns>
        public static bool WriteTxt(string log, string filepath)
        {
            try
            {
                string folder = filepath.Substring(0, filepath.LastIndexOf('\\'));
                // 创建目录
                if (Directory.Exists(folder) == false)
                {
                    Directory.CreateDirectory(folder);
                }
                // 当文件不存在时创建文件
                if (File.Exists(filepath) == false)
                {
                    FileStream fs = File.Create(filepath);
                    fs.Close();
                }
                // 写入文件内容
                File.AppendAllText(filepath, log + "\r\n", System.Text.Encoding.Default);
                return true;
            }
            catch
            {
                return false;
            }
        }


		
	}
}
